package com.ruge.tool.redisson;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @author ruge.wu
 * @version 2021-10-19 12:01
 **/
public class RedissonDistributedLocker implements DistributedLocker {


    private RedissonClient redissonClient;

    public RedissonDistributedLocker(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * lock(), 拿不到lock就不罢休，不然线程就一直block
     *
     * @param lockKey key
     * @return {@link RLock}
     */
    @Override
    public RLock lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        System.out.println("上锁:" + lockKey);
        return lock;
    }

    /**
     * timeout为加锁时间，单位为秒
     *
     * @param lockKey key
     * @param timeout 超时时间 默认秒
     * @return {@link RLock}
     */
    @Override
    public RLock lock(String lockKey, long timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, TimeUnit.SECONDS);
        return lock;
    }

    /**
     * timeout为加锁时间，时间单位由unit确定
     *
     * @param lockKey key
     * @param unit    时间单位
     * @param timeout 超时时间
     * @return {@link RLock}
     */
    @Override
    public RLock lock(String lockKey, TimeUnit unit, long timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        return lock;
    }

    /**
     * tryLock()，马上返回，拿到lock就返回true，不然返回false。
     * 带时间限制的tryLock()，拿不到lock，就等一段时间，超时返回false.
     *
     * @param lockKey   key
     * @param unit      时间单位
     * @param waitTime  等待时间
     * @param leaseTime 超时时间
     * @return 是否拿到了锁
     */
    @Override
    public boolean tryLock(String lockKey, TimeUnit unit, long waitTime, long leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 解锁
     *
     * @param lockKey key
     */
    @Override
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
        System.out.println("释放锁:" + lockKey);
    }

    /**
     * 解锁
     *
     * @param lock {@link RLock}
     */
    @Override
    public void unlock(RLock lock) {
        lock.unlock();
    }
}
